package xworker.swt.data.listeners;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Control;
import org.xmeta.ActionContext;
import org.xmeta.Thing;
import xworker.dataObject.DataStore;
import xworker.dataObject.DataStoreListener;

import java.util.Map;

public class SwtDataStoreListener implements DataStoreListener {
    Thing thing;
    ActionContext actionContext;

    public SwtDataStoreListener(Thing thing, ActionContext actionContext){
        this.thing = thing;
        this.actionContext = actionContext;
    }

    @Override
    public void onReconfig(DataStore dataStore, Thing dataObject) {
        thing.doAction("onReconfig", actionContext, "dataStore", dataStore, "dataObject", dataObject, "listener", this);
    }

    @Override
    public void onLoaded(DataStore dataStore) {
        thing.doAction("onLoaded", actionContext, "dataStore", dataStore, "listener", this);
    }

    @Override
    public void onTotalCountUpdated(DataStore dataStore) {

    }

    @Override
    public void onChanged(DataStore dataStore) {
        thing.doAction("onChanged", actionContext, "dataStore", dataStore, "listener", this);
    }

    @Override
    public void beforeLoad(DataStore dataStore, Thing condition, Map<String, Object> params) {
        thing.doAction("beforeLoad", actionContext, "dataStore", dataStore, "params", params, "condition", condition, "listener", this);
    }

    public static SwtDataStoreListener create(ActionContext actionContext){
        Thing self = actionContext.getObject("self");

        Control control = self.doAction("getControl", actionContext);
        if(control == null){
            if(actionContext.get("parent") instanceof Control){
                control = actionContext.getObject("parent");
            }
        }
        DataStore dataStore = self.doAction("getDataStore", actionContext);

        SwtDataStoreListener listener = new SwtDataStoreListener(self, actionContext);
        dataStore.addListener(listener);

        if(control != null && !control.isDisposed()){
            control.addListener(SWT.Dispose, event -> dataStore.removeListener(listener));
        }

        actionContext.g().put(self.getMetadata().getName(), listener);

        return listener;
    }
}
